<template>
  <div class="boss">
    <!-- 顶部 -->
    <div class="top">
      <p>
        <span>是否显示</span>
        <!-- <el-input v-model="input" placeholder="请选择"></el-input> -->
        <el-select
          v-model="tableData.flag"
          placeholder="请选择"
          @change="onChange"
        >
          <el-option label="全选" :value="-1" />
          <el-option label="关闭" :value="false" />
          <el-option label="开启" :value="true" />
        </el-select>
      </p>

      <p>
        <span>秒杀名称:</span
        ><el-input v-model="search" placeholder="请输入秒杀名称" />
      </p>
    </div>
    <div class="add">
      <el-button type="primary" style="margin-left: 22px" @click="add()"
        >添加秒杀配置</el-button
      >
    </div>
    <!-- 表格-->
    <el-table
      :data="
        filterTrue.filter(
          data =>
            !search || data.name.toLowerCase().includes(search.toLowerCase())
        )
      "
      style="width: 100%"
    >
      >
      <el-table-column label="ID" prop="id" />
      <el-table-column label="秒杀名称" prop="name" />

      <el-table-column label="秒杀时段" prop="time" />

      <el-table-column label="轮播图" prop="img">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.img"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="110">
        <el-switch
          v-model="scope.row.flag"
          slot-scope="scope"
          active-color="skyblue"
          inactive-color="#eee"
      /></el-table-column>
      <el-table-column label="创建时间" prop="timestamp" />
      <el-table-column align="center" label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
          <el-button size="mini" type="primary" @click="addShop"
            >添加商品</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="时间范围" required>
          <el-col :span="11">
            <el-form-item prop="date1">
              <el-date-picker
                v-model="ruleForm.date1"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="date2">
              <el-time-picker
                v-model="ruleForm.date2"
                placeholder="选择时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="幻灯片" prop="name">
          <!-- <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload> -->
          <el-upload action="#" list-type="picture-card" :auto-upload="false">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img class="el-upload-list__item-thumbnail" :src="file.url" />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="ruleForm.delivery" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页 -->
    <div class="paging">
      <span />
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="currentChange"
      />
    </div>
  </div>
</template>

<script>
import { apiSeckill, apiGoodsAdd, apiGoodsSet, apiGoodsDel } from "@/api/index";
export default {
  name: "Allocation",
  data() {
    // 数据
    return {
      operation: "", // 判断弹框是什么类型
      tableData: [], // 接受mock数据的数组
      filterTrue: [], // 筛选true/false数据
      search: "", // 模糊搜索
      input: "", // 是否显示
      dialogVisible: false, // 控制弹框
      // dialogImageUrl: "", //目前不清楚
      disabled: false, //弹出上传图片弹框
      // dialogimg: false, //目前不清楚
      imageUrl: "", // 上传图片
      pageIndex: 1, // 默认起始页
      pageSize: 5, // 每页数据
      total: 0, // 总数据
      // form表单用到的属性
      ruleForm: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        title: "", // 上传评论
        imgUrl: "" // 上传图片地址
      },
      // 正则验证的东西
      rules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 1, max: 50, message: "最多50个字符", trigger: "blur" }
        ],
        region: [
          { required: true, message: "请选择活动区域", trigger: "change" }
        ]
      },
      form: {}
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created() {
    const res = await apiSeckill({
      pageIndex: this.pageIndex,
      pageSize: this.pageSize
    });
    console.log(res, "Res");
    this.tableData = res.list;
    this.total = res.total;
    this.filterTrue = res.list;
    // apiSeckill().then(res => {
    //   console.log(res, "res");
    //   this.tableData = res.list;
    //   this.filterTrue = res.list;
    //   this.total = res.total;
    // });
  },
  methods: {
    handleRemove(file) {
      // // 1.获取将要删除图片的临时路径
      // const filePath = file.response.data.tmp_path;
      // // 2.从pics数组中，找到图片对应的索引值
      // const i = this.formData.pics.findIndex((x) => x.pic === filePath);
      // // 3.调用splice方法，移除图片信息
      // this.formData.splice(i, 1);
      console.log(file, "删除");
    },
    // 弹框图片发大
    handlePictureCardPreview(file) {
      this.ruleForm.img = file.url; // 图片赋值路径
      this.dialogimg = true; // 图片弹框开启
    },
    // 图片上传
    handleDownload(file) {
      this.ruleForm.img = file.url; // 图片赋值路径
    },
    // 添加商品
    addShop() {
      this.$router.push("./addShop");
    },
    // 实现分页功能
    async currentChange(value) {
      this.pageIndex = value;
      const res = await apiSeckill({
        pageIndex: this.pageIndex,
        pageSize: this.pageSize
      });
      // const res2 = await apiGetInfo()
      // console.log("res", res);
      this.tableData = res.list;
      this.filterTrue = res.list;
      this.total = res.total;
    },
    // 开启关闭状态切换
    onChange(val) {
      console.log(val, "val");
      this.filterTrue = this.tableData.filter(item => {
        return item.flag === val || val === -1;
      });
      // [...this.filterTrue];
      // this.tableData = this.filterTrue;
    },
    // 图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    // 图片格式
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 删除功能
    handleDelete(index, row) {
      console.log(index, row, "1");
      this.filterTrue.splice(index, 1); // 直接删除筛选后的新数组
      apiGoodsDel({
        id: row.id
      }).then(() => {
        this.currentChange(this.pageIndex);
      });
    },
    // 点击叉号关闭弹窗
    handleClose(done) {
      // this.$confirm("确认关闭？")
      //   .then(_ => {
      //   })
      //   .catch(_ => {});
      done();
    },
    // 新增功能
    add() {
      this.operation = "add";
      this.dialogVisible = true;
    },
    // 编辑功能
    async handleEdit(index, row) {
      console.log(row, "row"); // 打印这行的信息
      this.operation = "set";
      this.dialogVisible = true; // 打开弹窗
      this.ruleForm = { ...row }; // 弹窗的内容等于当前选择行的内容
    },
    // 确定功能
    confirm() {
      this.$refs["ruleForm"].validate(valid => {
        console.log(this.ruleForm, "!23");
        if (valid) {
          // 如果都满足可以提交
          this.dialogVisible = false;
          if (this.operation === "set") {
            // this.tableData.forEach((item, index) => {
            //   if (item.id === this.ruleForm.id) {
            //     item.name = this.ruleForm.name;
            //     item.img = this.ruleForm.img;
            //     // array length vue diff 不会触发更新
            //     // 数组的长度不发生改变vue不会更新
            //     // this.$set(this.tableData, index, this.ruleForm);
            //   }
            // });
            apiGoodsSet({
              id: this.ruleForm.id,
              name: this.ruleForm.name
            }).then(() => {
              // 刷新列表
              this.currentChange(this.pageIndex);
            });
          } else if (this.operation === "add") {
            // this.ruleForm.id = Math.random() * 100000000000000000;
            // this.tableData.push(this.ruleForm);
            apiGoodsAdd({
              name: this.ruleForm.name
            }).then(() => {
              // 刷新列表
              this.currentChange(this.pageIndex);
            });
          }
          // 清空弹出框
          this.ruleForm = {
            name: "",
            region: "",
            date1: "",
            date2: "",
            delivery: false
          };
        } else {
          // 否则不可以
          return false;
        }
      });
      // console.log(this.form, "form");
    }
  }
};
</script>
<!-- css样式 -->
<style lang="scss" scoped>
.top {
  width: 100%;
  display: flex;
  align-items: center;
  p {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-left: 25px;

    span {
      width: 50%;
    }
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.box {
  margin: 20px;
  border: 1px solid #ccc;
}
.paging {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 10px;
}
</style>
